from re import T
from PyQt5.QtWidgets import  QWidget,QPushButton,QMessageBox,QFileDialog,QVBoxLayout,QLabel,QGroupBox,QFormLayout,QComboBox,QHBoxLayout,QLineEdit,QTextEdit
from PyQt5.QtCore import  pyqtSignal
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import Qt
import subprocess
from datetime import datetime
import os
import platform
import tempfile
import resources

class FolderTreeView(QWidget):
    img_selected = pyqtSignal(str)
    crop_req = pyqtSignal()  # 添加信号用于传递矩形参数
    save_req = pyqtSignal()
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        # 1. 创建垂直布局对象
        vbox = QVBoxLayout()

        btn1 = QPushButton(QIcon(':/icons/open.png'),' 打开', self)
        btn1.setCursor(Qt.PointingHandCursor)
        btn1.clicked.connect(self.open_image)

        btn4 = QPushButton(QIcon(':/icons/screenshot.png'),' 截图', self)
        btn4.setCursor(Qt.PointingHandCursor)
        btn4.clicked.connect(self.adb_screenshot)

        btn2 = QPushButton(QIcon(':/icons/crop.png'),' 裁剪', self)
        btn2.setCursor(Qt.PointingHandCursor)
        btn2.clicked.connect(self.crop_image)

        btn3 = QPushButton(QIcon(':/icons/save.png'),' 保存', self)
        btn3.setCursor(Qt.PointingHandCursor)
        btn3.clicked.connect(self.save_image)

        vbox.addWidget(btn1)
        vbox.addWidget(btn4)
        vbox.addWidget(btn2)
        vbox.addWidget(btn3)
        vbox.addSpacing(10)
        
        # 添加矩形参数显示区域
        self.rect_group = QGroupBox("区域")
        self.rect_group.setMaximumHeight(150)  # 最大高度250像素
        rect_layout = QFormLayout()
        
        self.x_label = QLabel("-")
        self.y_label = QLabel("-")
        self.width_label = QLabel("-")
        self.height_label = QLabel("-")

        self.area_field = QLineEdit()
        self.area_field.setReadOnly(True)

        rect_layout.addRow("X:", self.x_label)
        rect_layout.addRow("Y:", self.y_label)
        rect_layout.addRow("宽度:", self.width_label)
        rect_layout.addRow("高度:", self.height_label)

        rect_layout.addRow("坐标:", self.area_field)
        
        self.rect_group.setLayout(rect_layout)
        vbox.addWidget(self.rect_group)
        vbox.addSpacing(10)


         # 创建水平布局
        hbox = QHBoxLayout()
         # 设置控件之间的间距
        hbox.setSpacing(5)

        # 创建下拉菜单
        combo_box = QComboBox(self)
        
        # 向下拉菜单添加选项
        combo_box.addItem("找图","find_img")
        combo_box.addItem("找色","find_color")
        combo_box.addItem("比色","compare_color")
        hbox.addWidget(combo_box)
        
         # 添加按钮
        add_cdoe = QPushButton('生成代码')
        add_cdoe.setObjectName("add_cdoe_btn")
        add_cdoe.setCursor(Qt.PointingHandCursor)
        hbox.addWidget(add_cdoe)

        

        # 添加一组选项
        # items = ["选项 5", "选项 6", "选项 7"]
        # self.combo_box.addItems(items)
        vbox.addLayout(hbox)

        self.area_input = QTextEdit()
        self.area_input.setReadOnly(True)
        vbox.addWidget(self.area_input)

        vbox.addStretch(1)

        self.tip_group = QGroupBox("操作提示")
        tip_layout = QFormLayout()
        tip_layout.addRow("选择区域:",QLabel("Alt+鼠标拖动"))
        tip_layout.addRow("取消区域:",QLabel("ESC"))
        tip_layout.addRow("拖动图片:",QLabel("Ctrl+鼠标拖动"))
        tip_layout.addRow("图色参数:",QLabel("鼠标右键操作"))
        self.tip_group.setLayout(tip_layout)
        vbox.addWidget(self.tip_group)
        # 4. 将布局应用到窗口
        self.setLayout(vbox)


    def show_message(self):
        # 显示消息框
        QMessageBox.information(self, '提示', '按钮被点击了！')    

    def open_image(self):
        """打开图像文件
        
        显示文件选择对话框，允许用户选择一个或多个图像文件。
        如果当前标签页为空，则在当前标签页打开第一个文件，
        否则为每个文件创建新标签页。
        """
        file_paths, _ = QFileDialog.getOpenFileNames(
            self, "打开图像", "", 
            "图像文件 (*.png *.jpg *.jpeg *.bmp *.tif *.tiff)"
        )
        
        if not file_paths:
            return    

        self.img_selected.emit(file_paths[0])    
        
    def display_rect_params(self, rect_params):
        # 显示矩形参数
        self.x_label.setText(f"{int(rect_params['x'])}")
        self.y_label.setText(f"{int(rect_params['y'])}")
        self.width_label.setText(f"{int(rect_params['width'])}")
        self.height_label.setText(f"{int(rect_params['height'])}")
        self.area_field.setText(f"{int(rect_params['x'])},{int(rect_params['y'])},{int(rect_params['width'])},{int(rect_params['height'])}")

    def clear_rect_params(self):
        # 清除矩形参数
        self.x_label.setText("-")
        self.y_label.setText("-")
        self.width_label.setText("-")
        self.height_label.setText("-")
        self.area_field.setText("-")    

    def crop_image(self):
        self.crop_req.emit()

    def save_image(self):
        self.save_req.emit()

    def adb_screenshot(self):
         # 创建临时文件路径
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        file_name = f"screenshot_{timestamp}.png"
        temp_path = os.path.join(tempfile.gettempdir(), file_name)
        self.take_screenshot(temp_path)
        self.img_selected.emit(temp_path) 

    def check_adb_available(self):
        """检查ADB是否可用"""
        try:
            subprocess.run(
                ["adb", "version"], 
                check=True, 
                stdout=subprocess.PIPE, 
                stderr=subprocess.PIPE,
                text=True
            )
            return True
        except (subprocess.CalledProcessError, FileNotFoundError):
            return False

    def check_device_connected(self):
        """检查是否有设备连接"""
        try:
            result = subprocess.run(
                ["adb", "devices"], 
                check=True, 
                stdout=subprocess.PIPE, 
                stderr=subprocess.PIPE,
                text=True
            )
            # 检查输出中是否有设备
            return len(result.stdout.splitlines()) > 2
        except subprocess.CalledProcessError:
            return False   

    def take_screenshot(self,output_path=None):
        """
        使用ADB截取屏幕并保存到文件
        
        参数:
            output_path: 保存截图的路径，默认为当前目录下的screenshot_时间戳.png
        """
        # 检查ADB是否可用
        if not self.check_adb_available():
            QMessageBox.information(self, '提示', '错误: 未找到ADB，请确保ADB已添加到系统PATH中')
            return False

        # 检查设备是否连接
        if not self.check_device_connected():
            QMessageBox.information(self, '提示', '错误: 未检测到已连接的Android设备，请确保设备已启用调试模式并连接')
            return False

        # 设置默认输出路径
        if not output_path:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_path = f"screenshot_{timestamp}.png"

        try:
            # 执行ADB截图命令
            result = subprocess.run(
                ["adb", "shell", "screencap", "-p"],
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                check=True
            )

            # 处理Windows系统的换行问题
            if platform.system() == "Windows":
                # Windows上需要替换回车符
                screenshot_data = result.stdout.replace(b'\r\n', b'\n')
            else:
                screenshot_data = result.stdout

            # 保存截图到文件
            with open(output_path, "wb") as f:
                f.write(screenshot_data)

            #print(f"截图已保存到: {os.path.abspath(output_path)}")
            return True

        except subprocess.CalledProcessError as e:
            #print(f"执行ADB命令失败: {e.stderr.decode('utf-8', errors='ignore')}")
            QMessageBox.information(self, '提示', f"执行ADB命令失败: {e.stderr.decode('utf-8', errors='ignore')}")
            return False
        except IOError as e:
            QMessageBox.information(self, '提示', f"保存文件失败: {str(e)}")
            return False        
        